import { createApp, watch, readonly } from 'vue'
import { createPinia } from 'pinia'
import { globalDataFromParentStore } from '@/stores/globalDataFromParentStore'

import App from './App.vue'
import routerData, { beforeEach, beforeResolve, afterEach } from './router/index'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import './main.css'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import { createRouter } from 'vue-router'
import _ from 'lodash'
import permission from '@/utils/v-permission'

let _$__key = ''
function render(props) {
  const { container } = props
  const app = createApp(App)
  app.use(createPinia())
  app.directive('permission', permission)
  _$__key = container ? props.activeRule : ''
  const router = createRouter({
    ...routerData(_$__key),
  })
  app.use(router)
  app.use(ElementPlus)
  const target = container ? container.querySelector('#app') : '#app'
  app.directive('permission', permission)
  app.mount(target)
  window.$provideDataFromeParent = (key) => {
    let _$_globalDataFromParent_$_ = window._$_globalDataFromParent_$_ || {}
    if (key) {
      const value = _$_globalDataFromParent_$_
        ? _$_globalDataFromParent_$_[_$__key]?.[key]
        : undefined
      if (value === undefined) {
        throw new Error(`${key} is not exist`)
      }
      return value
    } else {
      return _$_globalDataFromParent_$_[_$__key] ? _$_globalDataFromParent_$_[_$__key] : null
    }
  }
  window.$sendParentMessage = () => {}
  if (container) {
    app.config.globalProperties.$globalDataFromParent = readonly({
      ...props.globalData,
    })
    const globalDataFromParentStores = globalDataFromParentStore()
    globalDataFromParentStores.setInfo(props.globalData)
    // 设置向父级通信的全局事件
    window.$sendParentMessage = (data) => {
      const event = new CustomEvent('childAppEvent', {
        detail: {
          appMsg: props,
          data: data,
        },
      })
      window.dispatchEvent(event)
    }
    props.onGlobalStateChange((state, prev) => {
      globalDataFromParentStores.setChangeInfo(state)
    })
    watch(
      () => globalDataFromParentStores.changeInfo,
      (newValue, oldValue) => {
        if (!_.isEqual(newValue, oldValue)) {
          props.setGlobalState({ ...newValue })
        }
      },
      { deep: true },
    )
  }
  // 路由全局守卫 前置
  router.beforeEach((to, from, next) => {
    return beforeEach(to, from, next)
  })
  // 全局前置守卫
  router.beforeResolve((to) => {
    return beforeResolve(to)
  })
  // 全局后置钩子
  router.afterEach((to, from, failure) => {
    return afterEach(to, from, failure)
  })
}

const initQianKun = () => {
  renderWithQiankun({
    mount(props) {
      render(props)
    },
    bootstrap() {
      console.log('bootstrap')
    },
    unmount() {
      console.log('unmount')
    },
    update(props) {
      console.log('update', props)
    },
  })
}
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({})
}

initQianKun()
